#include "XUtility.h"

std::string XUtility::str_2_hex(const char * value, int value_len)
{
	std::string ret_str;
	char buf[40] = {0};	

	const char * buffer = value;
	int buffer_size = value_len;
	for(int i = 0 ;i < buffer_size; i++) {
		sprintf(buf,"%02X",(unsigned char)buffer[i]);		
		ret_str += buf;
	}	
	return ret_str;
}

std::string XUtility::str_2_hex(const std::string& value)
{
	std::string ret_str;
	char buf[40] = {0};	

	const char * buffer = value.c_str();
	int buffer_size = value.length();
	for(int i = 0 ;i < buffer_size; i++) {
		sprintf(buf,"%02X",(unsigned char)buffer[i]);		
		ret_str += buf;
	}	
	return ret_str;
}

std::string XUtility::hex_2_str(const std::string& value)
{
	const char* src = value.c_str();
	int length = value.length();
	char dst[ length<<1 ];

	for ( int i=0; i < length/2; i++ ) {
		dst[i] = 0;
		if (src[i<<1]>='A' && src[i<<1]<='F') {
			dst[i] += 16*(src[i<<1]-55);
		} else {
			dst[i] += 16*(src[i<<1]-'0');
		}
		if (src[(i<<1)+1]>='A' && src[(i<<1)+1]<='F') {
			dst[i] += src[(i<<1)+1]-55;
		} else {
			dst[i] += src[(i<<1)+1]-'0';
		}
	}

	return std::string( dst, length>>1);
}

std::string XUtility::uint64_2_string(uint64_t v)
{	
	const int MAX_BUF_SIZE = 40;
	char buf[MAX_BUF_SIZE];
#if __WORDSIZE == 64
	snprintf(buf, MAX_BUF_SIZE-1, "%lu", v);
#else
	snprintf(buf, MAX_BUF_SIZE-1, "%llu", v);
#endif
	return buf;
}

std::string XUtility::uint32_2_string(uint32_t v)
{	
	const int MAX_BUF_SIZE = 40;
	char buf[MAX_BUF_SIZE];

	snprintf(buf, MAX_BUF_SIZE-1, "%u", v);

	return buf;
}

std::string XUtility::int32_2_string(int32_t v)
{	
	const int MAX_BUF_SIZE = 40;
	char buf[MAX_BUF_SIZE];

	snprintf(buf, MAX_BUF_SIZE-1, "%d", v);

	return buf;
}

std::string XUtility::time_2_string(time_t time, const char* format)
{
	const int SIZE = 255;
	char buf[SIZE] = {0};
	
	time_t t = time;
	struct tm cur_tm;
	localtime_r(&t,&cur_tm);
	
	strftime(buf,SIZE,format,&cur_tm);

	return buf;
}

std::string XUtility::time_2_string(uint64_t time, const char* format)
{
	return time_2_string((time_t)(time / 1000000),format) + " " + uint64_2_string(time % 1000000);
}

